package com.budwk.app.enterprise.controllers.admin;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.budwk.app.miniapp.common.enums.ProblemFeedbackEnum;
import com.budwk.app.miniapp.common.enums.WxEventEnum;
import com.budwk.app.miniapp.models.ProblemFeedback;
import com.budwk.app.miniapp.services.ProblemFeedbackService;
import com.budwk.app.sys.models.SmsMsgDTO;
import com.budwk.app.sys.services.OpaSmsService;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.common.result.ResultCode;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.common.page.PageUtil;
import com.budwk.starter.log.annotation.SLog;
import com.budwk.starter.security.utils.SecurityUtil;
import com.budwk.app.enterprise.models.BusinessInformation;
import com.budwk.app.enterprise.services.BusinessinformationService;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.*;
import org.nutz.lang.Strings;
import com.budwk.starter.common.openapi.annotation.*;
import lombok.extern.slf4j.Slf4j;
import org.nutz.mvc.upload.TempFile;
import org.nutz.mvc.upload.UploadAdaptor;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@IocBean
@At("/platform/enterprise/enterprise/business/information")
@ApiDefinition(tag = "企业信息")
@Slf4j
public class BusinessinformationController{

    @Inject
    private BusinessinformationService wxBusinessInformationService;

    @Inject
    private ProblemFeedbackService problemFeedbackService;

    @Inject
    OpaSmsService opaSmsService;

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "分页查询企业信息")
    @ApiFormParams(
        value = {
            @ApiFormParam(name = "pageNo", example = "1", description = "页码", type = "integer"),
            @ApiFormParam(name = "pageSize", example = "10", description = "页大小", type = "integer"),
            @ApiFormParam(name = "pageOrderName", example = "createdAt", description = "排序字段"),
            @ApiFormParam(name = "pageOrderBy", example = "descending", description = "排序方式")
        },
        implementation = BusinessInformation.class
    )
    @ApiResponses(
    implementation = BusinessInformation.class
    )
    @SaCheckPermission("wx.business.information")
    public Result<?> list(@Param("..")BusinessInformation bean,@Param("pageNo") int pageNo, @Param("pageSize") int pageSize, @Param("pageOrderName") String pageOrderName, @Param("pageOrderBy") String pageOrderBy) {
        Cnd cnd = Cnd.NEW();
        if (Strings.isNotBlank(pageOrderName) && Strings.isNotBlank(pageOrderBy)) {
            cnd.orderBy(pageOrderName, PageUtil.getOrder(pageOrderBy));
        }

        if (bean.getCompanyName() !=null && Strings.isNotBlank(bean.getCompanyName().toString())) {
            cnd.and("companyName","=",bean.getCompanyName());
        }

        if (bean.getPreviousName() !=null && Strings.isNotBlank(bean.getPreviousName().toString())) {
            cnd.and("previousName","=",bean.getPreviousName());
        }

        if (bean.getLegalRepresentative() !=null && Strings.isNotBlank(bean.getLegalRepresentative().toString())) {
            cnd.and("legalRepresentative","=",bean.getLegalRepresentative());
        }

        if (bean.getBusinessStatus() !=null && Strings.isNotBlank(bean.getBusinessStatus().toString())) {
            cnd.and("businessStatus","=",bean.getBusinessStatus());
        }

        if (bean.getDateOfEstablishment() !=null && Strings.isNotBlank(bean.getDateOfEstablishment().toString())) {
            cnd.and("dateOfEstablishment","=",bean.getDateOfEstablishment());
        }

        if (bean.getRegisteredCapital() !=null && Strings.isNotBlank(bean.getRegisteredCapital().toString())) {
            cnd.and("registeredCapital","=",bean.getRegisteredCapital());
        }

        if (bean.getPaidInCapital() !=null && Strings.isNotBlank(bean.getPaidInCapital().toString())) {
            cnd.and("paidInCapital","=",bean.getPaidInCapital());
        }

        if (bean.getTaxpayerIdentificationNumber() !=null && Strings.isNotBlank(bean.getTaxpayerIdentificationNumber().toString())) {
            cnd.and("taxpayerIdentificationNumber","=",bean.getTaxpayerIdentificationNumber());
        }

        if (bean.getOrganizationCode() !=null && Strings.isNotBlank(bean.getOrganizationCode().toString())) {
            cnd.and("organizationCode","=",bean.getOrganizationCode());
        }

        if (bean.getTaxpayerQualification() !=null && Strings.isNotBlank(bean.getTaxpayerQualification().toString())) {
            cnd.and("taxpayerQualification","=",bean.getTaxpayerQualification());
        }

        if (bean.getDateOfApproval() !=null && Strings.isNotBlank(bean.getDateOfApproval().toString())) {
            cnd.and("dateOfApproval","=",bean.getDateOfApproval());
        }

        if (bean.getIndustry() !=null && Strings.isNotBlank(bean.getIndustry().toString())) {
            cnd.and("industry","=",bean.getIndustry());
        }

        if (bean.getNationalStandardIndustry() !=null && Strings.isNotBlank(bean.getNationalStandardIndustry().toString())) {
            cnd.and("nationalStandardIndustry","=",bean.getNationalStandardIndustry());
        }

        if (bean.getScaleOfPersonnel() !=null && Strings.isNotBlank(bean.getScaleOfPersonnel().toString())) {
            cnd.and("scaleOfPersonnel","=",bean.getScaleOfPersonnel());
        }

        if (bean.getEnglishName() !=null && Strings.isNotBlank(bean.getEnglishName().toString())) {
            cnd.and("englishName","=",bean.getEnglishName());
        }

        if (bean.getRegisteredAddress() !=null && Strings.isNotBlank(bean.getRegisteredAddress().toString())) {
            cnd.and("registeredAddress","=",bean.getRegisteredAddress());
        }

        if (bean.getSocialCreditCode() !=null && Strings.isNotBlank(bean.getSocialCreditCode().toString())) {
            cnd.and("socialCreditCode","=",bean.getSocialCreditCode());
        }

        if (bean.getBusinessRegistrationNumber() !=null && Strings.isNotBlank(bean.getBusinessRegistrationNumber().toString())) {
            cnd.and("businessRegistrationNumber","=",bean.getBusinessRegistrationNumber());
        }

        if (bean.getBusinessPeriod() !=null && Strings.isNotBlank(bean.getBusinessPeriod().toString())) {
            cnd.and("businessPeriod","=",bean.getBusinessPeriod());
        }

        if (bean.getTypeOfEnterprise() !=null && Strings.isNotBlank(bean.getTypeOfEnterprise().toString())) {
            cnd.and("typeOfEnterprise","=",bean.getTypeOfEnterprise());
        }

        if (bean.getNumberInsuredPersons() !=null && Strings.isNotBlank(bean.getNumberInsuredPersons().toString())) {
            cnd.and("numberInsuredPersons","=",bean.getNumberInsuredPersons());
        }

        if (bean.getNumberInsuredBranches() !=null && Strings.isNotBlank(bean.getNumberInsuredBranches().toString())) {
            cnd.and("numberInsuredBranches","=",bean.getNumberInsuredBranches());
        }

        if (bean.getRegistrationAuthority() !=null && Strings.isNotBlank(bean.getRegistrationAuthority().toString())) {
            cnd.and("registrationAuthority","=",bean.getRegistrationAuthority());
        }

        if (bean.getScopeOfBusiness() !=null && Strings.isNotBlank(bean.getScopeOfBusiness().toString())) {
            cnd.and("scopeOfBusiness","=",bean.getScopeOfBusiness());
        }

        if (bean.getTelephone() !=null && Strings.isNotBlank(bean.getTelephone().toString())) {
            cnd.and("telephone","=",bean.getTelephone());
        }

        if (bean.getLetterBox() !=null && Strings.isNotBlank(bean.getLetterBox().toString())) {
            cnd.and("letterBox","=",bean.getLetterBox());
        }

        if (bean.getOfficialWebsite() !=null && Strings.isNotBlank(bean.getOfficialWebsite().toString())) {
            cnd.and("officialWebsite","=",bean.getOfficialWebsite());
        }

        return Result.data(wxBusinessInformationService.listPage(pageNo, pageSize, cnd));
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "新增企业信息")
    @ApiFormParams(
        implementation = BusinessInformation.class
    )
    @ApiResponses
    @SLog(tag = "新增企业信息", value = "${args[0].id}")
    @SaCheckPermission("wx.business.information.create")
    public Result<?> create(@Param("..")BusinessInformation wxBusinessInformation , HttpServletRequest req) {
        wxBusinessInformation .setCreatedBy(SecurityUtil.getUserId());
        wxBusinessInformationService.insert( wxBusinessInformation );
        return Result.success();
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "修改企业信息")
    @ApiFormParams(
        implementation = BusinessInformation.class
    )
    @ApiResponses
    @SLog(tag = "修改企业信息", value = "${args[0].id}")
    @SaCheckPermission("wx.business.information.update")
    public Result<?> update(@Param("..")BusinessInformation wxBusinessInformation , HttpServletRequest req) {
        wxBusinessInformation.setUpdatedBy(SecurityUtil.getUserId());
        wxBusinessInformationService.updateIgnoreNull( wxBusinessInformation );
        return Result.success();
    }

    @At("/get")
    @Ok("json")
    @POST
    @ApiOperation(name = "获取企业信息")
    @ApiFormParams(
        {
            @ApiFormParam(name = "id", description = "唯一标识",required = true, check = true)
        }
    )
    @SaCheckPermission("wx.business.information")
    public Result<?> getData(@Param("id")String id, HttpServletRequest req) {
        BusinessInformation wxBusinessInformation  = wxBusinessInformationService.fetch(id);
        if ( wxBusinessInformation  == null) {
            return Result.error(ResultCode.NULL_DATA_ERROR);
        }
        return Result.data( wxBusinessInformation );
    }

    @At("/delete")
    @Ok("json")
    @POST
    @ApiOperation(name = "删除企业信息")
    @ApiFormParams(
        {
            @ApiFormParam(name = "id", description = "唯一标识",required = true, check = true)
        }
    )
    @SLog(tag = "删除企业信息", value = "${args[0]}")
    @SaCheckPermission("wx.business.information.delete")
    public Result<?> delete(@Param("id")String id, HttpServletRequest req) {
        BusinessInformation wxBusinessInformation  = wxBusinessInformationService.fetch(id);
        if ( wxBusinessInformation  == null) {
            return Result.error(ResultCode.NULL_DATA_ERROR);
        }
        wxBusinessInformationService.delete(id);
        req.setAttribute("_slog_msg", wxBusinessInformation .getId());
        return Result.success();
    }


    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "企业问题反馈")
    public Result<?> getProblemPageList(@Param("pageNo") int pageNo, @Param("pageSize") int pageSize,@Param("..") ProblemFeedback problemFeedback) {
        Cnd cnd = Cnd.NEW();
        cnd.desc(ProblemFeedback::getCreatedAt);
        if(StrUtil.isNotBlank(problemFeedback.getProblem())){
            cnd.and(ProblemFeedback::getProblem,"like","%"+problemFeedback.getProblem()+"%");
        }
        if(StrUtil.isNotBlank(problemFeedback.getName())){
            cnd.and(ProblemFeedback::getName,"=",problemFeedback.getName());
        }
        if(StrUtil.isNotBlank(problemFeedback.getUsername())){
            cnd.and(ProblemFeedback::getUsername,"=",problemFeedback.getUsername());
        }
        if(StrUtil.isNotBlank(problemFeedback.getUsername())){
            cnd.and(ProblemFeedback::getTel,"=",problemFeedback.getTel());
        }
        if(StrUtil.isNotBlank(problemFeedback.getDepts())){
            cnd.and(ProblemFeedback::getDepts,"like","%"+problemFeedback.getProblem()+"%");
        }
        if(StrUtil.isNotBlank(problemFeedback.getAuditStatus())){
            cnd.and(ProblemFeedback::getAuditStatus,"=",problemFeedback.getAuditStatus());
        }
        return Result.data(problemFeedbackService.listPage(pageNo,pageSize,cnd));
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "企业问题单位修改")
    public Result<?> urdateDept(@Param("..") ProblemFeedback problemFeedback) {
        SmsMsgDTO smsMsgDTO = new SmsMsgDTO();
        Set<String> phones =new HashSet<>();
        if(StrUtil.isNotEmpty(problemFeedback.getDepts())){
            Arrays.stream(problemFeedback.getDepts().split("、"))
                    .collect(Collectors.toList()).forEach(s->{
                        phones.add(ProblemFeedbackEnum.getPhoneByCommunity(s));
                    });
        }
        smsMsgDTO.setPhoneNumberSet(phones);
        smsMsgDTO.setTemplateParamList(Lists.newArrayList(StrUtil.format("您收到一条待处理的企业反馈信息详情查看：http://140.210.211.155:10118/{} \n请及时与反馈人员联系并进行12345工单流程处理。",problemFeedback.getId())));
        opaSmsService.opaSmsSendOneMessage(smsMsgDTO);
        return Result.success();
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "企业问题反馈")
    public Result<?> problemFeedback(@Param("..") ProblemFeedback problemFeedback) {
        problemFeedback.setAuditStatus("未完结");
        problemFeedbackService.insert(problemFeedback);


        SmsMsgDTO smsMsgDTO = new SmsMsgDTO();
        Set<String> phones =new HashSet<>();
        if(StrUtil.isNotEmpty(problemFeedback.getDepts())){
            Arrays.stream(problemFeedback.getDepts().split("、"))
                    .collect(Collectors.toList()).forEach(s->{
                phones.add(ProblemFeedbackEnum.getPhoneByCommunity(s));
            });
        }
        smsMsgDTO.setPhoneNumberSet(phones);
        smsMsgDTO.setTemplateParamList(Lists.newArrayList(StrUtil.format("您收到一条待处理的企业反馈信息详情查看：http://140.210.211.155:10118/{} \n请及时与反馈人员联系并进行12345工单流程处理。",problemFeedback.getId())));        opaSmsService.opaSmsSendOneMessage(smsMsgDTO);

        smsMsgDTO = new SmsMsgDTO();
        smsMsgDTO.setPhoneNumberSet(Sets.newHashSet(problemFeedback.getTel()));
        smsMsgDTO.setTemplateParamList(Lists.newArrayList("已收到您的问题反馈，已详细记录并会尽快安排工作人员进行回访处理。请您留意接听我们的回访电话，感谢您的支持与理解！"));
        opaSmsService.opaSmsSendOneMessage(smsMsgDTO);
        return Result.success(problemFeedback);
    }
    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "企业问题反馈")
    public Result<?> auditStatus(@Param("id") String id) {
        ProblemFeedback problemFeedback=   problemFeedbackService.fetch(id);
        problemFeedback.setAuditStatus("已完结");
        problemFeedbackService.updateIgnoreNull(problemFeedback);
        return Result.success();
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "企业问题删除")
    public Result<?> delProblem(@Param("ids") List<String> ids ) {
        problemFeedbackService.clear(Cnd.where(ProblemFeedback::getId,"in",ids));
        return Result.success();
    }

    @At
    @Ok("json")
    @GET
    @ApiOperation(name = "企业问题反馈")
    public Result<?> getProblem(@Param("id") String id ) {
        return Result.data(problemFeedbackService.fetch(id));
    }

    @At
    @Ok("json")
    @GET
    @ApiOperation(name = "查询所有公司列表")
    public Result<?> listCompanys() {
        return Result.data(wxBusinessInformationService.listCompanys());
    }

    @AdaptBy(type = UploadAdaptor.class, args = {"ioc:fileUpload"})
    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "导入企业信息")
    @ApiFormParams(
            value = {@ApiFormParam(name = "file", description = "文件对象名")},
            mediaType = "multipart/form-data"
    )
    @SaCheckLogin
    public Result<?> importCompanyData(@Param("file") TempFile file) {
        wxBusinessInformationService.importCompanyData(file);
        return Result.success();
    }
}
